import React, { PureComponent } from 'react'
import { connect } from 'dva'
import { FormattedMessage } from 'umi/locale'
import { Form, Icon, Input, Button, Checkbox, Alert, message } from 'antd'
import Geetest from '@/components/Geetest'
import { codeMessage } from '@/utils/codeMessage'
import styles from './Login.less'

const FormItem = Form.Item

@connect(({ login, loading }) => ({
  login,
  submitting: loading.effects['login/login'],
}))
class LoginPage extends PureComponent {
  state = {
    type: 'account',
    autoLogin: true,
    captchaObj: { getValidate() {} },
  }

  componentDidMount = () => {
    const { dispatch } = this.props
    // init geetest
    dispatch({
      type: 'login/getCaptcha'
    })
  }

  handleSubmit = (e) => {
    e.preventDefault()

    const { captchaObj } = this.state
    const { form, dispatch } = this.props

    const results = captchaObj.getValidate()
    if (results) {
      this.setState(state => ({
          ...state,
          ...results
        }),
        () => {
          form.validateFields((err, values) => {
            if (!err) {
              const { type } = this.state
              dispatch({
                type: 'login/login',
                payload: {
                  ...values,
                  ...this.state,
                  type,
                },
              })
            }
          })
        }
      )
    } else {
      message.error('滑块儿验证失败')
    }
  }

  changeAutoLogin = e => {
    this.setState(() => ({
      autoLogin: e.target.checked,
    }))
  }

  handlerGeetest = captchaObj => {
    this.setState(() => ({
      captchaObj
    }))
  }

  renderMessage = errcode => (
    <Alert style={{ marginBottom: 24 }} message={codeMessage[errcode]} type="error" showIcon />
  )

  render() {
    const { form, login, submitting } = this.props
    const { autoLogin } = this.state
    const { getFieldDecorator } = form
    const payload = { ...login.geetest, handlerGeetest: this.handlerGeetest }

    return (
      <Form onSubmit={this.handleSubmit} className={styles.loginForm}>
        {!login.status && login.type === 'account' && !submitting && this.renderMessage(login.errcode)}
        <FormItem>
          {getFieldDecorator('username', {
            rules: [{ required: true, message: '请输入您的账户!' }],
          })(
            <Input size="large" name="username" prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} type="text" placeholder="请输入账户" />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: '请输入您的密码!' }],
          })(
            <Input size="large" name="password" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="请输入密码" />
          )}
        </FormItem>
        <Geetest {...payload} />
        <section>
          <Checkbox checked={autoLogin} onChange={this.changeAutoLogin}>
            <FormattedMessage id="app.login.remember-me" />
          </Checkbox>
          <Button size="large" type="primary" htmlType="submit" loading={submitting} block className={styles.loginFormButton}>
            登录
          </Button>
        </section>
      </Form>
    )
  }
}

const WrappedNormalLoginForm = Form.create()(LoginPage)

export default WrappedNormalLoginForm